package com.gwcm.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gwcm.exception.BusinessException;
import com.gwcm.mapper.*;
import com.gwcm.model.dto.user.UserQueryRequest;
import com.gwcm.model.entity.*;
import com.gwcm.model.vo.UserMemberCardVo;
import com.gwcm.model.vo.UserRoleVo;
import com.gwcm.model.vo.UserVo;
import com.gwcm.service.IUserService;
import com.gwcm.util.PageUtil;
import com.yhz.commonutil.constant.SortConstant;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 15375
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2023-02-28 20:12:05
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private MemberCardMapper memberCardMapper;

    @Resource
    private UserMemberCardMapper userMemberCardMapper;


    /**
     * 用户分页查询
     * @param userQueryRequest 查询条件
     * @return
     * @throws BusinessException
     */
    @Override
    public IPage<UserVo> pageList(UserQueryRequest userQueryRequest) throws BusinessException {
        IPage<User> page = PageUtil.vaildPageParam(userQueryRequest.getCurrent(), userQueryRequest.getPageSize());
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();

        if (StrUtil.isBlank(sortOrder) || !StrUtil.equalsAny(sortOrder, SortConstant.SORT_ORDER_ASC, SortConstant.SORT_ORDER_DESC)) {
            //默认按升序排序
            sortOrder = SortConstant.SORT_ORDER_ASC;
        }
        userQueryRequest.setSortField(sortField);
        userQueryRequest.setSortOrder(sortOrder);
        IPage<UserVo>  userToIPage = userMapper.selectUserToPage(page, userQueryRequest);
        IPage<UserVo>  userVoIPage =  userToIPage.convert(item -> {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(item, userVo);
            return userVo;
        });

        return userVoIPage;
    }
    @Override
    public User getUserByUserName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = baseMapper.selectOne(wrapper);
        return user;
    }

    /**
     * 根据ID查询user
     *
     * @param userId
     * @return
     */
    public UserVo selectUserById(Long userId){
        //通过userId查到user
        User user = userMapper.selectUserById(userId);
        //通过userId对应userMemberCard中用户id
        QueryWrapper<UserMemberCard> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        UserMemberCard userMemberCard = userMemberCardMapper.selectOne(wrapper);
        List<Role> roleList= selectUserRole(userId);
        UserRoleVo userRoleVo = new UserRoleVo();
        userRoleVo.setRoleList(roleList);

        if(userMemberCard != null){//如果用户是会员
            //通过memberCardId查到memberCard
            Long memberCardId = userMemberCard.getMemberCardId();
            MemberCard memberCard = memberCardMapper.selectById(memberCardId);
            //通过memberCard获得cardName
            String cardName = memberCard.getCardName();
            UserMemberCardVo userMemberCardVo = new UserMemberCardVo();
            userMemberCardVo.setCardName(cardName);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String time2 = sdf.format(userMemberCard.getEndTime());
            userMemberCardVo.setExpireTime(time2);

            UserVo userVo = new UserVo();
            userVo.setUserMemberCardVo(userMemberCardVo);
            userVo.setUserRoleVo(userRoleVo);
            BeanUtils.copyProperties(user, userVo);
            return userVo;
        }else {
            UserVo userVo = new UserVo();
            userVo.setUserRoleVo(userRoleVo);
            BeanUtils.copyProperties(user, userVo);
            return userVo;
        }
    }

    /**
     * 根据username查询user
     * @param username
     * @return
     */
    public User selectUserByUsername(String username){
        return userMapper.selectUserByUsername(username);
    }

    /**
     * 查询user集合
     * @param user
     * @return
     */
    public List<User> selectUserList(User user){
        return userMapper.selectUserList(user);
    }

//    /**
//     * 删除用户
//     * @param userId
//     * @return
//     */
//    public int deleteUserById(Long userId){
//        userRoleMapper.deleteUserRoleByUserId(userId);
//        return userMapper.deleteUserById(userId);
//    }

//    /**
//     * 新增用户-角色信息
//     * 前端需传递roles数组
//     * @param user
//     */
//    public void insertUserRole(User user){
//        Long[] roles = user.getRoleIds();
//        if(roles.length > 0){
//            //新增用户与角色管理
//            List<UserRole> list = new ArrayList<UserRole>();
//            for(Long roleId : roles){
//                UserRole ur = new UserRole();
//                ur.setUserId(user.getId());
//                ur.setRoleId(roleId);
//                list.add(ur);
//            }
//            if(list.size() > 0){
//                userRoleMapper.batchUserRole(list);
//            }
//        }
//    }

    /**
     * 新增用户角色组信息
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if(roleIds.length > 0){
            //新增用户与角色管理
            List<UserRole> list = new ArrayList<UserRole>();
            for(Long roleId : roleIds){
                UserRole ur = new UserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                ur.setCreateTime(new Date());
                ur.setUpdateTime(new Date());
                list.add(ur);
            }
            if(list.size() > 0){
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 用户角色授权
     * @param userId
     * @param roleIds
     */
    public void insertUserAuth(Long userId, Long[] roleIds){
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 检查用户名是否唯一
     * @param nickname
     * @return
     */
    public boolean checkNicknameUnique(String nickname){
        int count = userMapper.checkNicknameUnique(nickname);
        return count > 0 ? true : false;
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    public int updateUser(User user){
        int count = 0;
        if(!checkNicknameUnique(user.getNickname())){
            count = userMapper.updateUser(user);
        }
        return count;
    }

//        /**
//     * 查询用户的角色组Id
//     * 前端需求ROLE_admin,ROLE_user
//     * @param userId
//     * @return
//     */
//    public String selectUserRoleGroup(Long userId){
//        List<Role> list = roleMapper.selectRolesByUserId(userId);
//        if(list.size() > 0){
////            String s = list.stream().map(Role::getId).toString();
////            System.out.println(s+"我的结果是");
////            System.out.println(list+"列表结果是");
//            return list.stream().map(Role::getRoleKey).collect(Collectors.joining(","));
//        } else {
//            return null;
//        }
//    }

    /**
     * 查询用户的角色
     * 前端需求ROLE_admin,ROLE_user
     * @param userId
     * @return
     */
    public List<Role> selectUserRole(Long userId){
        List<Role> list = roleMapper.selectRolesByUserId(userId);
        if(list.size() > 0){
            return list;
        } else {
            return null;
        }
    }

    /**
     * 查询已登录用户角色组
     * @param user
     * @return
     */
    public String selectUserRoleGroup(User user){
        List<Role> list = selectUserRole(user.getId());
        if(list.size() > 0){
            return list.stream().map(Role::getRoleKey).collect(Collectors.joining(","));
        } else {
            return "";
        }
    }

//    /**
//     * 新增用户-会员卡信息
//     * 前端需传递memberCards数组
//     * @param user
//     */
//    public void insertUserMemberCard(User user){
//        Long[] memberCards = user.getRoleIds();
//        if(roles.length > 0){
//            //新增用户与角色管理
//            List<UserRole> list = new ArrayList<UserRole>();
//            for(Long roleId : roles){
//                UserRole ur = new UserRole();
//                ur.setUserId(user.getId());
//                ur.setRoleId(roleId);
//                list.add(ur);
//            }
//            if(list.size() > 0){
//                userRoleMapper.batchUserRole(list);
//            }
//        }
//    }
}




